<template>
  <el-select
    v-model="selects" :allow-create="allowCreate" :disabled="disabled" :placeholder="placeholder" default-first-option
    :multiple-limit="multipleLimit" filterable multiple @change="trimChange()"
  >
    <el-option v-for="item in options" :key="item" :label="item" :value="item"/>
  </el-select>
</template>

<script>
export default {
  name: "StringFormatMulSelect",

  props: {
    value: {
      type: Array, default: function () {
        return []
      }
    },
    placeholder: {type: String, default: null},
    options: {
      type: Array, default: function () {
        return []
      }
    },
    formatFunction: {
      type: Function, default: function (val) {
        return val
      }
    },
    filterFunction: {
      type: Function, default: function () {
        return true
      }
    },
    disabled: {type: Boolean, default: false},
    multipleLimit: {type: Number, default: 0},
    allowCreate: {type: Boolean, default: false},
  },

  data() {
    return {
      selects: []
    }
  },

  watch: {
    'value': {
      handler(val) {
        this.selects = val
      }, immediate: true
    },

    'selects': {
      handler(val) {
        this.$emit('input', val)
      }, immediate: true
    }
  },

  methods: {
    trimChange() {
      let result = [];
      for (let i = 0; i < this.selects.length; i++) {
        const ele = this.formatFunction(this.selects[i]);
        if (this.filterFunction(ele)) {
          if (!result.includes(ele)) {
            result.push(ele)
          } else {
            result = result.filter(item => item !== ele)
          }
        }
      }
      this.selects = result
    }
  }
}
</script>

<style scoped>

</style>
